package com.kwlt.smc.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
 * Http服务推送
 * @author xushunxin
 *
 */
public class SendHttpUtils {

	public static String sendHttpPostRequest(String strUrl,
			Map<String, String> paramentMap,String returnCode) {
		URL url;
		HttpURLConnection httpConn;
		StringBuffer sb = new StringBuffer();
		StringBuffer parament = new StringBuffer();
		try {
			url = new URL(strUrl);
			httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setDoOutput(true);
			httpConn.setRequestMethod("POST");
			httpConn.setRequestProperty("content-type",
					"application/x-www-form-urlencoded");
			for (Map.Entry<String, String> entry : paramentMap.entrySet()) {
				if (StringUtils.isBlank(entry.getKey()))
					parament.append(URLEncoder.encode(entry.getValue(), returnCode)
							+ "&");
				else
					parament.append(entry.getKey() + "="
							+ URLEncoder.encode(entry.getValue(), returnCode)
							+ "&");
			}
			if (StringUtils.isBlank(parament.toString()))
				return "9999";
			if (parament.toString().endsWith("&")) {
				parament.setLength(parament.length() - 1);
			}
			httpConn.setRequestProperty("Content-Length",
					String.valueOf(parament.toString().getBytes().length));
			httpConn.getOutputStream().write(parament.toString().getBytes());
			httpConn.getOutputStream().flush();
			httpConn.getOutputStream().close();
			InputStream is = httpConn.getInputStream();
			int nRead;
			byte[] bBuffer = new byte[1024];
			do {
				nRead = is.read(bBuffer);
				if (nRead <= 0)
					break;
				sb.append(new String(bBuffer, 0, nRead, returnCode));
			} while (true);
		} catch (Exception e) {
			System.out.println(strUrl+"?"+parament.toString());
			e.printStackTrace();
		}
		return sb.toString();
	}
}
